<?php
/**
 * Created by PhpStorm.
 * User: liuqi.
 * Date: 2017/11/15 14:54.
 */

namespace home\Controller;


class DrugController extends ApibaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    /*
   * 药品信息维护列表
   */
    public function index()
    {
        $page    = I('get.page', 1);
        $perpage = 10;
        $url     = [];
        $list    = M('Druglist');
        if (trim(I('get.drug_no'))) {
            $list           = $list->where(['drug_no' => trim(I('get.drug_no'))]);
            $url['drug_no'] = I('get.drug_no');
        }
        if (trim(I('get.drug_name'))) {
            $list             = $list->where("drug_name LIKE '%".trim(I('get.drug_name')) ."%'");
            $url['drug_name'] = I('get.drug_name');
        }
        $copyObject = clone $list;
        $getData    = $list->order(['id' => 'desc'])->page($page, $perpage)->select();

        $this->assign('page', setPage($copyObject->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData', $getData);
        $this->display('drug/index');
    }

    /**
     * 添加/修改药品种类
     */
    public function addDrugKind()
    {
        if (I('post.dosubmit')) {
            $exist = M('Druglist')->where(['drug_no' => trim(I('post.drug_no'))])->find();
            if ($exist) {
                $this->showtips('药品编号已存在');
            }
            $data['drug_no']   = trim(I('post.drug_no'));
            $data['type']      = trim(I('post.type'));
            $data['drug_name'] = trim(I('post.drug_name'));
            $data['drug_size'] = trim(I('post.drug_size'));
            $data['drug_unit'] = trim(I('post.drug_unit'));
            $data['update_at'] = time();
            if (I('post.id')) {
                $id     = intval(I('post.id'));
                $update = M('Druglist')->where(['id' => $id])->setField($data);
                if ($update) {
                    $this->showtips('修改成功');
                }
            }
            $data['add_at'] = time();
            $add            = M('Druglist')->add($data);
            if ($add) {
                $this->showtips('添加成功');
            } else {
                $this->showtips('添加失败');
            }
        } elseif (I('get.id')) {
            if (S('drug_info_' . I('get.id'))) {
                $getData = S('drug_info_' . I('get.id'));
            } else {
                $id      = intval(I('get.id'));
                $getData = M('Druglist')->where(['id' => $id])->find();
                S('drug_info_' . $id, $getData, 3600);
            }
            $this->assign('getData', $getData);
        }
        $kinds = M('ConfigSet')->getFieldByConfigColumn('drugType', 'config_val');
        $kinds = explode(',', $kinds);
        $this->assign('kinds', $kinds);
        $this->display('drug/add_drug_kind');
    }

    /**
     * 删除药品种类  如果该种类有过入库信息  无法删除
     */
    public function delDrugKind()
    {
        if (I('get.id')) {
            $drug_id = intval(I('get.id'));
            $exist   = M('Instock')->where(['drug_id' => $drug_id])->find();
            if ($exist) {
                $this->showtips('该药品种类已入库，无法删除');
            }
            $del = M('Druglist')->where(['id' => $drug_id])->delete();
            if ($del) {
                $this->showtips('删除成功');
            } else {
                $this->showtips('删除失败');
            }
        }
    }

    /*
     * 药品入库信息列表
     */
    public function drugList()
    {
        /*参数初始化*/
        $page    = I('get.page', 1);
        $perpage = 10;
        $stime   = I('get.stime');
        $etime   = I('get.etime');
        $url     = [];
        $list    = M('Instock')->where(['delete_at' => 0]);
        if (trim(I('get.drug_no'))) {
            $list           = $list->where(['drug_no' => trim(I('get.drug_no'))]);
            $url['drug_no'] = trim(I('get.drug_no'));
        }
        if (trim(I('get.drug_name'))) {
            $list             = $list->where(['drug_name' => trim(I('get.drug_name'))]);
            $url['drug_name'] = trim(I('get.drug_name'));
        }
        if (trim(I('get.warehouse'))) {
            $list             = $list->where(['warehouse' => intval(I('get.warehouse'))]);
            $url['warehouse'] = trim(I('get.warehouse'));
        }
        if ($stime && !$etime) {
            $list         = $list->where(['add_at' => ['gt', strtotime($stime)]]);
            $url['stime'] = $stime;
        } elseif (!$stime && $etime) {
            $list         = $list->where(['add_at' => ['lt', strtotime($etime)]]);
            $url['etime'] = $etime;
        } elseif ($stime && $etime) {
            $list         = $list->where(['add_at' => ['between', [strtotime($stime), strtotime($etime) + 86400]]]);
            $url['stime'] = $stime;
            $url['etime'] = $etime;
        }
        $copyObject = clone $list;
        $getData    = $list->order(['add_at' => 'desc'])->page($page, $perpage)->select();
        $warehouse  = M('Warehouse')->select();
        foreach ($warehouse as $k => $v) {
            $new_warehouse[ $v['warehouse_id'] ] = $v['warehouse_name'];
        }
        foreach ($getData as $k => $v) {
            $drug_info                  = M('Druglist')->where(['id' => $v['drug_id']])->find();
            $getData[ $k ]['type']      = $drug_info['type'];
            $getData[ $k ]['drug_size'] = $drug_info['drug_size'];
            $getData[ $k ]['drug_unit'] = $drug_info['drug_unit'];
            $getData[ $k ]['warehouse'] = $new_warehouse[ $v['warehouse'] ];
        }
        $warehouse = M('Warehouse')->field('warehouse_id,warehouse_code,warehouse_name')->select();
        $this->assign('page', setPage($copyObject->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData', $getData);
        $this->assign('warehouse', $warehouse);
        $this->display('drug/drug_list');
    }

    /**
     * 药品入库//修改药品（药品可更改）
     *
     */
    //    public function addDrug(){
    //        if(I('post.dosubmit')){
    //            var_dump(I('post.'));exit;
    //            if(I('post.in_stock') <0 || !is_numeric(I('post.in_stock'))){
    //                $this->showtips('入库数量有误，请输入输入');
    //            }
    //            $data['type'] = I('post.type');
    //            $data['drug_no'] = I('post.drug_no');
    //            $data['drug_name'] = I('post.drug_name');
    //            $data['drug_size'] = I('post.drug_size');
    //            $data['drug_unit'] = I('post.drug_unit');
    //            $data['in_stock'] = I('post.in_stock');
    //            $data['warehouse'] = I('post.warehouse');
    //            $data['operator_id'] = session('loginUid');
    //            $data['storage_name'] = I('post.storage_name');
    //            $data['update_at'] = time();
    //            $Instock = M('Instock');
    //            $Druglist = M('Druglist');
    //            $Instock->startTrans();
    //
    //            if(I('post.id')){
    //                //修改
    //                $info = M('Instock')->where(['id'=>I('post.id')])->find();
    //                $changeNum = I('post.in_stock') - $info['in_stock'];
    //                $oldDrugNo = $info['drug_no'];
    //                $nowDrugNo = I('post.drug_no');
    //                $getStock = $Druglist->where(['drug_no'=>$oldDrugNo])->getField('stock_num');
    //                if($oldDrugNo == $nowDrugNo){
    //                    //药品编号没有更改
    //                    $updateArr['warehouse'] = I('post.warehouse');
    //                    $updateArr['in_stock'] = I('post.in_stock');
    //                    $updateArr['operator_id'] = session('loginUid');
    //                    $updateArr['storage_name'] = I('post.storage_name');
    //                    $updateArr['update_at'] = I('post.storage_name');
    //                    if($changeNum < 0){
    //                        if($getStock < abs($changeNum)){
    //                            $this->showtips('库存不足，修改失败');
    //                        }
    //                    }
    //                    $update = $Druglist->where(['drug_no'=>$oldDrugNo])->setInc('stock_num',$changeNum);
    //                    if($update){
    //                        $re = $Instock->where(['id'=>I('post.id')])->setField($updateArr);
    //                        if($re){
    //                            $Instock->commit();
    //                            $Druglist->commit();
    //                            $this->showtips('修改成功');
    //                        }else{
    //                            $Druglist->rollback();
    //                            $this->showtips('修改失败');
    //                        }
    //                    }else{
    //                        $this->showtips('修改失败');
    //                    }
    //                }else{
    //                    //药品更改
    //                    if($getStock < $info['in_stock']){
    //                        $this->showtips('库存不足，修改失败');
    //                    }
    //                    $update = $Druglist->where(['drug_no'=>$oldDrugNo])->setDec('stock_num',$info['in_stock']);
    //                    if($update){
    //                        $changeStock = $Druglist->where(['drug_no'=>$nowDrugNo])->setInc('stock_num',I('post.in_stock'));
    //                        if($changeStock){
    //                            $re = $Instock->where(['id'=>I('post.id')])->setField($data);
    //                            if($re){
    //                                $Instock->commit();
    //                                $Druglist->commit();
    //                                $this->showtips('修改成功');
    //                            }else{
    //                                $Druglist->rollback();
    //                                $this->showtips('修改失败');
    //                            }
    //                        }else{
    //                            $Druglist->rollback();
    //                            $this->showtips('修改失败');
    //                        }
    //                    }else{
    //                        $this->showtips('修改失败');
    //                    }
    //                }
    //            }
    //            $data['add_at'] = time();
    //            $add = $Instock->add($data);
    //            if($add){
    //                $upd = $Druglist->where(['drug_no'=>I('post.drug_no')])->setInc('stock_num',I('post.in_stock'));
    //                if($upd){
    //                    $Instock->commit();
    //                    $Druglist->commit();
    //                    $this->showtips('添加成功');
    //                }else{
    //                    $Instock->rollback();
    //                    $this->showtips('添加失败');
    //                }
    //            }else{
    //                $this->showtips('添加失败');
    //            }
    //        }elseif (I('get.id')){
    //            $getData = M('Instock')->where(['id'=>I('get.id')])->find();
    //            $this->assign('getData',$getData);
    //            $this->assign('is_update',1);
    //        }
    //        $drug = M('Druglist')->select();
    //        $warehouse = M('ConfigSet')->getFieldByConfigColumn('depotType','config_val');
    //        $warehouse = explode(',',$warehouse);
    //        $this->assign('drug',$drug);
    //        $this->assign('warehouse',$warehouse);
    //        $this->display('drug/add_drug_stock');
    //    }

    /**
     * 药品入库
     */
    public function addDrug()
    {
        if (I('post.dosubmit')) {
            if (!I('post.drug_no')) {
                $this->showtips('请选择药品');
            }
            if (I('post.in_stock') < 0 || !is_numeric(I('post.in_stock'))) {
                $this->showtips('入库数量有误，请重新输入');
            }
            $drug_id  = intval(I('post.drug_id'));
            $Instock  = M('Instock');
            $Druglist = M('Druglist');
            $Stock    = M('Stock');
            $Instock->startTrans();
            $drug_name            = $Druglist->where(['id' => $drug_id])->getField('drug_name');
            $data['drug_id']      = $drug_id;
            $data['drug_no']      = trim(I('post.drug_no'));
            $data['drug_name']    = $drug_name;
            $data['type']         = trim(I('post.type'));
            $data['in_stock']     = intval(I('post.in_stock'));
            $data['warehouse']    = intval(I('post.warehouse'));
            $data['operator']     = getLoginUname();
            $data['storage_name'] = trim(I('post.storage_name'));
            $data['remark']       = htmlspecialchars(trim(I('post.remark')));
            $data['update_at']    = time();

            if (I('post.id')) {
                $id = intval(I('post.id'));
                //修改
                $info                      = M('Instock')->where(['id' => $id])->find();
                $changeNum                 = I('post.in_stock') - $info['in_stock'];
                $oldDrugNo                 = $info['drug_no'];
                $getStock                  = $Stock->where(['drug_id' => $drug_id, 'warehouse' => I('post.warehouse')])->getField('stock_num');
                $updateArr['warehouse']    = intval(I('post.warehouse'));
                $updateArr['in_stock']     = intval(I('post.in_stock'));
                $updateArr['operator']     = getLoginUname();
                $updateArr['storage_name'] = I('post.storage_name');
                $updateArr['update_at']    = time();
                if ($changeNum < 0) {
                    //更改的入库数量小于之前的 更改库存要确定 库存大于差值
                    if ($getStock < abs($changeNum)) {
                        $this->showtips('库存不足，修改失败');
                    }
                }
                if ($changeNum == '0') {
                    //入库数量没有更改
                    $re = $Instock->lock(true)->where(['id' => $id])->setField($updateArr);
                    if ($re) {
                        $Instock->commit();
                        $this->showtips('修改成功');
                    } else {
                        $this->showtips('修改失败[2]');
                    }
                }
                $update = $Stock->lock(true)->where(['drug_id' => $drug_id])->setInc('stock_num', $changeNum);
                if ($update) {
                    $re = $Instock->lock(true)->where(['id' => $id])->setField($updateArr);
                    if ($re) {
                        $Instock->commit();
                        $Druglist->commit();
                        $this->showtips('修改成功');
                    } else {
                        $Druglist->rollback();
                        $this->showtips('修改失败[0]');
                    }
                } else {
                    $this->showtips('修改失败[1]');
                }
            }
            $data['add_at'] = time();
            $add            = $Instock->add($data);
            if ($add) {
                $exist = $Stock->where(['drug_id' => $drug_id, 'warehouse' => trim(I('post.warehouse'))])->find();
                if ($exist) {
                    $edit = $Stock->lock(true)->where(['drug_id' => $drug_id, 'warehouse' => trim(I('post.warehouse'))])->setInc('stock_num', trim(I('post.in_stock')));
                    if ($edit) {
                        $Instock->commit();
                        $Stock->commit();
                        $this->showtips('添加成功');
                    } else {
                        $Instock->rollback();
                        $this->showtips('添加失败');
                    }
                } else {
                    $insert = $Stock->lock(true)->add(['drug_id' => $drug_id, 'drug_no' => I('post.drug_no'), 'drug_name' => $drug_name, 'warehouse' => I('post.warehouse'), 'type' => I('post.type'), 'stock_num' => I('post.in_stock'), 'add_at' => time(), 'update_at' => time()]);
                    if ($insert) {
                        $Instock->commit();
                        $Stock->commit();
                        $this->showtips('添加成功');
                    } else {
                        $Instock->rollback();
                        $this->showtips('添加失败[2]');
                    }
                }
            } else {
                $this->showtips('添加失败[1]');
            }
        } elseif (I('get.id')) {
            $getData = M('Instock')->where(['id' => I('get.id')])->find();
            $this->assign('getData', $getData);
            $this->assign('is_update', 1);
        }
        $drug      = M('Druglist')->select();
        $warehouse = M('Warehouse')->select();
        $this->assign('drug', $drug);
        $this->assign('warehouse', $warehouse);
        $this->display('drug/add_drug_stock');
    }

    /**
     * 药品库存查询
     */
    public function stockList()
    {
        $page    = I('get.page', 1);
        $perpage = I('get.perpage', 10);
        $url     = [];
        $list    = M('Stock');
        if (trim(I('get.drug_no'))) {
            $list           = $list->where(['drug_no' => trim(I('get.drug_no'))]);
            $url['drug_no'] = trim(I('get.drug_no'));
        }
        if (trim(I('get.drug_name'))) {
            $list             = $list->where(['drug_name' => trim(I('get.drug_name'))]);
            $url['drug_name'] = trim(I('get.drug_name'));
        }
        if (trim(I('get.warehouse'))) {
            $list             = $list->where(['warehouse' => trim(I('get.warehouse'))]);
            $url['warehouse'] = trim(I('get.warehouse'));
        }
        $copy      = clone $list;
        $getData   = $list->page($page, $perpage)->select();
        $warehouse = M('Warehouse')->select();
        foreach ($warehouse as $it => $vo) {
            $new_warehouse[ $vo['warehouse_id'] ] = $vo['warehouse_name'];
        }
        foreach ($getData as $k => $v) {
            if (S('drug_info_' . $v['drug_id'])) {
                $drug_info = S('drug_info_' . $v['drug_id']);
            } else {
                $drug_info = M('Druglist')->where(['id' => $v['drug_id']])->find();
                S('drug_info_' . $v['drug_id'], $drug_info, 3600);
            }
//            $drug_info                = M('Druglist')->where(['id' => $v['drug_id']])->find();
            $getData[ $k ]['type']      = $drug_info['type'];
            $getData[ $k ]['drug_name'] = $drug_info['drug_name'];
            $getData[ $k ]['drug_size'] = $drug_info['drug_size'];
            $getData[ $k ]['drug_unit'] = $drug_info['drug_unit'];
            $getData[ $k ]['warehouse'] = $new_warehouse[ $v['warehouse'] ];
        }
        $this->assign('page', setPage($copy->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData', $getData);
        $this->assign('warehouse', $warehouse);
        $this->display('drug/drug_stock');
    }

    /**
     * 入库的时候 选择药品获取对应信息
     */
    public function getDrugInfo()
    {
        if (I('post.id')) {
            $data = M('Druglist')->where(['id' => trim(I('post.id'))])->find();
            dataFormat($data, '0', 'success');
        } else {
            dataFormat('', 1, '参数有误');
        }
    }

    /**
     * 药品入库 删除功能
     */
    public function delInstock()
    {
        if (I('get.id')) {
            $id      = intval(I('get.id'));
            $Instock = M('Instock');
            $Stock   = M('Stock');
            $Instock->startTrans();
            $info = $Instock->where(['id' => $id, 'delete_at' => 0])->find();
            if ($info) {
                $stock_num = $Stock->where(['drug_id' => $info['drug_id'], 'warehouse' => $info['warehouse']])->getField('stock_num');
                if ($stock_num < $info['in_stock']) {
                    $this->showtips('库存不足，删除失败');
                }
                $res = $Stock->lock(true)->where(['drug_id' => $info['drug_id'], 'warehouse' => $info['warehouse']])->setDec('stock_num', $info['in_stock']);
                if ($res) {
                    $del = $Instock->lock(true)->where(['id' => $id])->setField(['update_at' => time(), 'delete_at' => time()]);
                    if ($del) {
                        $Instock->commit();
                        $Stock->commit();
                        $this->showtips('删除成功');
                    } else {
                        $Stock->rollback();
                        $this->showtips('删除失败[0]');
                    }
                } else {
                    $this->showtips('删除失败[1]');
                }
            } else {
                $this->showtips('参数有误[0]');
            }
        } else {
            $this->showtips('参数有误[1]');
        }
    }

    /**
     * 库存盘点列表
     */
    public function checkList()
    {
        $page    = I('get.page', 1);
        $perpage = I('get.perpage', 10);
        $url     = [];
        //起始时间
        $stime = I('get.stime');
        //结束时间
        $etime      = I('get.etime');
        $checkModel = M('Stockcheck')->where(['delete_at' => 0]);
        if (trim(I('get.drug_no'))) {
            $checkModel     = $checkModel->where(['drug_no' => trim(I('get.drug_no'))]);
            $url['drug_no'] = I('get.drug_no');
        }
        if (trim(I('get.drug_name'))) {
            $checkModel       = $checkModel->where(['drug_name' => trim(I('get.drug_name'))]);
            $url['drug_name'] = I('get.drug_name');
        }
        if ($stime && !$etime) {
            $checkModel   = $checkModel->where(['add_at' => ['gt', strtotime($stime)]]);
            $url['stime'] = $stime;
        } elseif (!$stime && $etime) {
            $checkModel   = $checkModel->where(['add_at' => ['lt', strtotime($etime)]]);
            $url['etime'] = $etime;
        } elseif ($stime && $etime) {
            $checkModel   = $checkModel->where(['add_at' => ['between', [strtotime($stime), strtotime($etime) + 86400]]]);
            $url['stime'] = $stime;
            $url['etime'] = $etime;
        }
        $copy          = clone $checkModel;
        $getData       = $checkModel->order(['id' => 'desc'])->page($page, $perpage)->select();
        $old_warehouse = M('Warehouse')->select();
        foreach ($old_warehouse as $it => $vo) {
            $new_warehouse[ $vo['warehouse_id'] ] = $vo['warehouse_name'];
        }
        foreach ($getData as $k => $v) {
            if (S('drug_info_' . $v['drug_id'])) {
                $drug_info = S('drug_info_' . $v['drug_id']);
            } else {
                $drug_info = M('Druglist')->where(['id' => $v['drug_id']])->find();
                S('drug_info_' . $v['drug_id'], $drug_info, 3600);
            }
            $getData[ $k ]['type']      = $drug_info['type'];
            $getData[ $k ]['drug_size'] = $drug_info['drug_size'];
            $getData[ $k ]['drug_unit'] = $drug_info['drug_unit'];
            $getData[ $k ]['warehouse'] = $new_warehouse[ $v['warehouse'] ];
        }
        $this->assign('page', setPage($copy->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData', $getData);
        $this->display('drug/check_list');
    }

    /**
     * 新建盘点
     */
    public function addCheck()
    {
        if (I('post.dosubmit')) {
            $drug_id = intval(I('post.drug_id'));
            if ($drug_id) {
                $drug_name = M('Druglist')->where(['id' => $drug_id])->getField('drug_name');
                $data      = ['drug_id' => $drug_id, 'drug_no' => trim(I('post.drug_no')), 'type' => I('post.type'), 'drug_name' => $drug_name, 'warehouse' => I('post.warehouse'), 'drug_size' => I('post.drug_size'), 'drug_unit' => I('post.drug_unit'), 'stock_num' => I('post.stock_num'), 'check_num' => intval(I('post.check_num')), 'lost_num' => I('post.lost_num'), 'check_user' => trim(I('post.check_user')), 'operator' => getLoginUname(), 'remark' => htmlspecialchars(trim(I('post.remark'))), 'add_at' => time(), 'update_at' => time()];
                $add       = M('Stockcheck')->add($data);
                if ($add) {
                    $this->showtips('新建成功');
                } else {
                    $this->showtips('新建失败');
                }
            } else {
                $this->showtips('参数有误');
            }
        }
        $warehouse = M('Warehouse')->select();
        $this->assign('warehouse', $warehouse);
        $this->display('drug/add_check');
    }

    /**
     * 获取 库存盘点信息
     */
    public function getCheckInfo()
    {
        if (I('post.warehouse') && I('post.id')) {
            $drug_id = intval(I('post.id'));
            $data    = M('Stock')->where(['warehouse' => I('post.warehouse'), 'drug_id' => $drug_id])->find();
            if ($data) {
                if (S('drug_info_' . $data['drug_id'])) {
                    $drug_info = S('drug_info_' . $data['drug_id']);
                } else {
                    $drug_info = M('Druglist')->where(['id' => $data['drug_id']])->find();
                    S('drug_info_' . $data['drug_id'], $drug_info, 3600);
                }
                $drug_info         = M('Druglist')->where(['id' => $data['drug_id']])->find();
                $data['type']      = $drug_info['type'];
                $data['drug_size'] = $drug_info['drug_size'];
                $data['drug_unit'] = $drug_info['drug_unit'];
                dataFormat($data, 0, 'success');
            } else {
                dataFormat('', 2, '未查到相关信息');
            }
        } else {
            dataFormat('', 1, '参数有误');
        }
    }

    /**
     * 删除盘点记录
     */
    public function delCheck()
    {
        if (I('get.id')) {
            $del = M('Stockcheck')->where(['id' => I('get.id')])->setField(['update_at' => time(), 'delete_at' => time()]);
            if ($del) {
                $this->showtips('删除成功');
            } else {
                $this->showtips('删除失败');
            }
        } else {
            $this->showtips('参数有误');
        }
    }


    /**
     * 月度仓库盘点列表
     */
    public function drugMonthList()
    {
        $nowMonth = ltrim(date('m'), '0');
        $nowYear  = date('Y');
        $page     = I('get.page', 1);
        $perpage  = I('get.perpage', 10);
        $year     = I('get.year', $nowYear);
        $month    = I('get.month', $nowMonth);

        $url   = [];
        $model = M('Stock s')->join('ymr_instock i ON s.drug_id = i.drug_id AND s.warehouse = i.warehouse')->where(['i.delete_at' => 0]);
        if (trim(I('get.warehouse'))) {
            $model            = $model->where(['s.warehouse' => intval(I('get.warehouse'))]);
            $url['warehouse'] = I('get.warehouse');
        }
        if (trim(I('get.type'))) {
            $model       = $model->where(['s.type' => trim(I('get.type'))]);
            $url['type'] = I('get.type');
        }
        if ($year && $month) {
            $stime = $year . '-' . $month;
            if ($month == '12') {
                $etime = ($year + 1) . '-1';
            } else {
                $etime = $year . '-' . ($month + 1);
            }
            $model        = $model->where(['i.add_at' => ['between', [strtotime($stime), strtotime($etime)]]]);
            $url['year']  = $year;
            $url['month'] = $month;
        }
        $model   = $model->group('i.drug_id,i.warehouse')->field('s.id,s.drug_id,s.drug_no,s.drug_name,s.stock_num,s.type,s.warehouse,SUM(i.in_stock) as month_in_num');
        $copy    = clone $model;
        $getData = $model->page($page, $perpage)->select();
//        var_dump($getData);exit;
//        echo $model->_sql();exit;
        $warehouse = M('Warehouse')->select();
        foreach ($warehouse as $it => $vo) {
            $new_warehouse[ $vo['warehouse_id'] ] = $vo['warehouse_name'];
        }
        foreach ($getData as $k => $v) {
            if (S('drug_info_' . $v['drug_id'])) {
                $drug_info = S('drug_info_' . $v['drug_id']);
            } else {
                $drug_info = M('Druglist')->where(['id' => $v['drug_id']])->find();
                S('drug_info_' . $v['drug_id'], $drug_info, 3600);
            }
            $getData[ $k ]['drug_size']     = $drug_info['drug_size'];
            $getData[ $k ]['drug_unit']     = $drug_info['drug_unit'];
            $getData[ $k ]['warehouse']     = $new_warehouse[ $v['warehouse'] ];
            $getData[ $k ]['month_use_num'] = M('Usedetail')->where(['drug_id' => $v['drug_id'], 'warehouse' => $v['warehouse']])->getField('sum(realuse_num) as relause_num') ? : 0;
        }
        $kinds = M('ConfigSet')->getFieldByConfigColumn('drugType', 'config_val');
        $kinds = explode(',', $kinds);
        $this->assign('page', setPage(count($copy->select()), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('kinds', $kinds);
        $this->assign('nowMonth', $nowMonth);
        $this->assign('nowYear', $nowYear);
        $this->assign('getData', $getData);
        $this->assign('warehouse', $warehouse);
        $this->display('drug/month_list');
    }

    /**
     *月度仓库盘点 添加备注
     */
    public function addMonthListRemark()
    {
        if (I('post.dosubmit')) {
            if (I('post.id')) {
                $id     = intval(I('post.id'));
                $update = M('Stock')->where(['id' => $id])->setField(['remark' => htmlspecialchars(I('post.remark')), 'update_at' => time()]);
                if ($update) {
                    $this->showtips('修改成功');
                } else {
                    $this->showtips('修改失败');
                }
            }
        } elseif (I('get.id')) {
            $getData = M('Stock')->where(['id' => I('get.id')])->find();
            $this->assign('getData', $getData);
        }
        $this->display('drug/add_month_remark');
    }

    /**
     * 药品领用统计列表
     */
    public function drugUseList()
    {
        $page    = I('get.page', 1);
        $perpage = I('get.perpage', 10);
        $stime   = I('get.stime');
        $etime   = I('get.etime');
        $url     = [];
//        $model   = M('Usedetail u')->join('ymr_drugtake d ON u.take_orderid = d.order_id')->where(['u.delete_at' => 0, 'u.is_outin' => 0])->group('u.take_orderid,u.drug_id,u.warehouse')->field('u.*,d.order_id,d.use_class,d.group_place,d.group_doctor,d.group_date,SUM(apply_num) as apply_num,SUM(take_num) as take_num,SUM(realuse_num) as realuse_num,SUM(last_num) as last_num,SUM(waste_num) as waste_num,SUM(cwwuse_num) as cwwuse_num');
        $model = M('Usedetail u')->join('ymr_drugtake d ON u.take_orderid = d.order_id')->where(['u.delete_at' => 0, 'u.is_outin' => 0])->field('u.*,d.order_id,d.use_class,d.group_place,d.group_doctor,d.group_date');
        if (trim(I('get.warehouse'))) {
            $model            = $model->where(['u.warehouse' => trim(I('get.warehouse'))]);
            $url['warehouse'] = trim(I('get.warehouse'));
        }
        if (trim(I('get.type'))) {
            $model       = $model->where(['u.take_type' => trim(I('get.type'))]);
            $url['type'] = trim(I('get.type'));
        }
        if (trim(I('get.group_place'))) {
            $model              = $model->where(['d.group_place' => trim(I('get.group_place'))]);
            $url['group_place'] = trim(I('get.group_place'));
        }
        if ($stime && !$etime) {
            $model        = $model->where(['u.add_at' => ['gt', strtotime($stime)]]);
            $url['stime'] = $stime;
        } elseif (!$stime && $etime) {
            $model        = $model->where(['u.add_at' => ['lt', strtotime($etime)]]);
            $url['etime'] = $etime;
        } elseif ($stime && $etime) {
            $model        = $model->where(['u.add_at' => ['between', [strtotime($stime), strtotime($etime)]]]);
            $url['stime'] = $stime;
            $url['etime'] = $etime;
        }
        $copy    = clone $model;
        $getData = $model->page($page, $perpage)->select();

//        echo $model->_sql();exit;
        $warehouse = M('Warehouse')->select();
        foreach ($warehouse as $itm => $vo) {
            $new_warehouse[ $vo['warehouse_id'] ] = $vo['warehouse_name'];
        }
        $kinds       = M('ConfigSet')->getFieldByConfigColumn('drugType', 'config_val');
        $kinds       = explode(',', $kinds);
        $group_place = M('Drugtake')->group('group_place')->where('group_place != ""')->field('group_place')->select();

        foreach ($getData as $k => $v) {
            if (S('drug_info_' . $v['drug_id'])) {
                $drug_info = S('drug_info_' . $v['drug_id']);
            } else {
                $drug_info = M('Druglist')->where(['id' => $v['drug_id']])->find();
                S('drug_info_' . $v['drug_id'], $drug_info, 3600);
            }
            $getData[ $k ]['drug_size'] = $drug_info['drug_size'];
            $getData[ $k ]['drug_unit'] = $drug_info['drug_unit'];
            $getData[ $k ]['drug_no']   = $drug_info['drug_no'];
            $getData[ $k ]['type']      = $drug_info['type'];
            $getData[ $k ]['drug_name'] = $drug_info['drug_name'];
            $getData[ $k ]['warehouse'] = $new_warehouse[ $v['warehouse'] ];
        }
        $this->assign('kinds', $kinds);
        $this->assign('group_place', $group_place);
        $this->assign('warehouse', $warehouse);
        $this->assign('page', setPage($copy->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData', $getData);
        $this->display('drug/drug_use_list');
    }

    /**
     * 耗材领用统计表
     */
    public function suppliesUseList()
    {
        $page    = I('get.page', 1);
        $perpage = I('get.perpage', 10);
        $stime   = I('get.stime');
        $etime   = I('get.etime');
        $url     = [];
//        $model   = M('Usedetail u')->join('ymr_drugtake d ON u.take_orderid = d.order_id')->where(['u.delete_at' => 0, 'u.is_outin' => 0])->group('u.take_orderid,u.drug_id,u.warehouse')->field('u.*,d.order_id,d.use_class,d.group_place,d.group_doctor,d.group_date,SUM(apply_num) as apply_num,SUM(take_num) as take_num,SUM(realuse_num) as realuse_num,SUM(last_num) as last_num,SUM(waste_num) as waste_num,SUM(cwwuse_num) as cwwuse_num');
        $model = M('Usedetail u')->join('ymr_material_take d ON u.take_orderid = d.order_id')->where(['u.delete_at' => 0, 'u.is_outin' => 0])->field('u.*,d.order_id,d.take_place,d.take_users,d.take_date');
        if (trim(I('get.warehouse'))) {
            $model            = $model->where(['u.warehouse' => trim(I('get.warehouse'))]);
            $url['warehouse'] = trim(I('get.warehouse'));
        }
        if (trim(I('get.type'))) {
            $model       = $model->where(['u.take_type' => trim(I('get.type'))]);
            $url['type'] = trim(I('get.type'));
        }
        if (trim(I('get.take_place'))) {
            $model              = $model->where(['d.take_place' => trim(I('get.take_place'))]);
            $url['take_place'] = trim(I('get.take_place'));
        }
        if ($stime && !$etime) {
            $model        = $model->where(['d.take_date' => ['gt', $stime]]);
            $url['stime'] = $stime;
        } elseif (!$stime && $etime) {
            $model        = $model->where(['d.take_date' => ['lt', $etime]]);
            $url['etime'] = $etime;
        } elseif ($stime && $etime) {
            $model        = $model->where(['d.take_date' => ['between', [$stime, $etime]]]);
            $url['stime'] = $stime;
            $url['etime'] = $etime;
        }
        $copy    = clone $model;
        $getData = $model->page($page, $perpage)->select();

//        echo $model->_sql();exit;
        $warehouse = M('Warehouse')->select();
        foreach ($warehouse as $itm => $vo) {
            $new_warehouse[ $vo['warehouse_id'] ] = $vo['warehouse_name'];
        }
        $kinds       = M('ConfigSet')->getFieldByConfigColumn('drugType', 'config_val');
        $kinds       = explode(',', $kinds);
        $take_place = M('MaterialTake')->group('take_place')->where('take_place != ""')->field('take_place')->select();
        foreach ($getData as $k => $v) {
            if (S('drug_info_' . $v['drug_id'])) {
                $drug_info = S('drug_info_' . $v['drug_id']);
            } else {
                $drug_info = M('Druglist')->where(['id' => $v['drug_id']])->find();
                S('drug_info_' . $v['drug_id'], $drug_info, 3600);
            }
            $getData[ $k ]['drug_size'] = $drug_info['drug_size'];
            $getData[ $k ]['drug_unit'] = $drug_info['drug_unit'];
            $getData[ $k ]['drug_no']   = $drug_info['drug_no'];
            $getData[ $k ]['type']      = $drug_info['type'];
            $getData[ $k ]['drug_name'] = $drug_info['drug_name'];
            $getData[ $k ]['warehouse'] = $new_warehouse[ $v['warehouse'] ];
        }
        $this->assign('kinds', $kinds);
        $this->assign('take_place', $take_place);
        $this->assign('warehouse', $warehouse);
        $this->assign('page', setPage($copy->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData', $getData);
        $this->display('drug/supplies_use_list');
    }

    /**
     * 仓库管理
     */
    public function warehouse()
    {
        $page      = I('get.page', 1);
        $perpage   = I('get.perpage', 10);
        $url       = [];
        $model     = M('Warehouse');
        $warehouse = $model->select();
        if (I('get.warehouse')) {
            $model            = $model->where(['warehouse_id' => I('get.warehouse')]);
            $url['warehouse'] = I('get.warehouse');
        }
        if (I('get.warehouse_code')) {
            $model                 = $model->where(['warehouse_code' => I('get.warehouse_code')]);
            $url['warehouse_code'] = I('get.warehouse_code');
        }
        if (I('get.contacts')) {
            $model           = $model->where(['contacts' => I('get.contacts')]);
            $url['contacts'] = I('get.contacts');
        }
        if (I('get.mobile')) {
            $model         = $model->where(['mobile' => I('get.mobile')]);
            $url['mobile'] = I('get.mobile');
        }
        $copy    = clone $model;
        $getData = $model->page($page, $perpage)->select();
        $this->assign('page', setPage($copy->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData', $getData);
        $this->assign('warehouse', $warehouse);
        $this->display('drug/warehouse');
    }

    /**
     * 添加/修改仓库
     */
    public function addWarehouse()
    {
        if (I('post.dosubmit')) {
            $data = [
                'warehouse_code'    => trim(I('post.warehouse_code')),
                'warehouse_name'    => trim(I('post.warehouse_name')),
                'warehouse_address' => trim(I('post.warehouse_address')),
                'contacts'          => trim(I('post.contacts')),
                'mobile'            => trim(I('post.mobile')),
                'remark'            => trim(I('post.remark')),
                'update_at'         => time()
            ];
            if (I('post.warehouse_id')) {
                $save = M('Warehouse')->where(['warehouse_id' => I('post.warehouse_id')])->setField($data);
                if ($save) {
                    $this->showtips('修改成功');
                } else {
                    $this->showtips('修改失败');
                }
            }
            $data['add_at'] = time();
            $add            = M('Warehouse')->add($data);
            if ($add) {
                $this->showtips('添加成功');
            } else {
                $this->showtips('添加失败');
            }
        } elseif (I('get.warehouse_id')) {
            $getData = M('Warehouse')->where(['warehouse_id' => I('get.warehouse_id')])->find();
            $this->assign('getData', $getData);
            $this->assign('is_update', 1);
        }
        $this->display('drug/add_warehouse');
    }

    /**
     * 删除仓库
     */
    public function delWarehouse()
    {
        if(I('get.id')){
            $exists = M('Instock')->where(['warehouse'=>intval(I('get.id'))])->count();
            if($exists){
                $this->showtips('该仓库已有入库记录，无法删除');
            }
            $del = M('Warehouse')->where(['warehouse_id'=>intval(I('get.id'))])->setField(['update_at'=>time(),'delete_at'=>time()]);
            if($del){
                $this->showtips('删除成功');
            }
        }
    }
}